<template>
  <div class="content">
    <div class="reporting-main">
      <div class="hd">
        <steps :step="2" :revise="isEditInfos" :editTitle="editTitle"></steps>
        <notice :title="alertTitle" :isShow="isShow"></notice>
      </div>
      <div class="bd">
        <div
          class="reporting-list module"
          v-for="item in signInfo"
          :key="item.imgType"
        >
          <div class="list-hd">
            <h3 class="title">
              <i class="icon" :class="iconChoose(item.imgType)"></i
              >{{ item.imgTitle
              }}<i
                class="color-red"
                style="font-weight: normal"
                v-if="item.isRequired == '1'"
                >（必填）</i
              >
            </h3>
            <div
              class="slide"
              @click="isShowExample = true"
              v-if="item.imgType == '1'"
            >
              <van-button class="example" plain type="info">示例图</van-button>
            </div>
          </div>
          <div class="list-bd">
            <p class="info">{{ item.imgIntro }}，最多 {{ item.maxNum }} 页</p>
            <div class="uploader-box">
              <van-uploader
                :class="{
                  'limit-uploader': verify.res == -1,
                }"
                v-model="item.regImages"
                multiple
                :max-count="item.maxNum"
                :max-size="5 * 1024 * 1024"
                :before-read="beforeAvatarUpload"
                :before-delete="handleRemove"
                @oversize="onOversize"
                :after-read="(file) => handleHttpRequest(file, item.imgType)"
              />
            </div>
          </div>
        </div>
        <div class="form-btn-wrap" v-if="verify.res != -1">
          <div class="form-btn" v-if="!isEditInfos">
            <van-button type="info" to="basicinfo">上一步</van-button>
            <van-button type="info" @click="onSubmit">下一步</van-button>
          </div>
          <div class="form-edit-btn" v-else>
            <van-button type="info" @click="onSubmit">确认修改</van-button>
          </div>
        </div>
        <div class="no-edit" v-else>
          <van-icon name="warning" />{{ verify.msg }}
        </div>
      </div>
    </div>
    <!-- 示例图弹出层 -->
    <van-popup v-model="isShowExample">
      <div class="exam-title">示例图</div>
      <div class="exam-content">
        <ul>
          <li>
            <div class="content-img">
              <span>完整清晰图</span>
              <van-image :src="require('../assets/images/example01.png')" />
            </div>
            <img
              class="icon_dx"
              :src="require('../assets/images/pic_d.png')"
              alt=""
            />
          </li>
          <li>
            <div class="content-img">
              <span>不完整图</span>
              <van-image :src="require('../assets/images/example02.png')" />
            </div>
            <img
              class="icon_dx"
              :src="require('../assets/images/pic_x.png')"
              alt=""
            />
          </li>
          <li>
            <div class="content-img">
              <span>不清晰图</span>
              <van-image :src="require('../assets/images/example03.png')" />
            </div>
            <img
              class="icon_dx"
              :src="require('../assets/images/pic_x.png')"
              alt=""
            />
          </li>
          <li>
            <div class="content-img">
              <span>干扰信息太多</span>
              <van-image :src="require('../assets/images/example04.png')" />
            </div>
            <img
              class="icon_dx"
              :src="require('../assets/images/pic_x.png')"
              alt=""
            />
          </li>
        </ul>
        <van-button type="info" class="know" @click="isShowExample = false"
          >我知道了</van-button
        >
      </div>
    </van-popup>
  </div>
</template>
<script>
import { Toast, Dialog } from "vant";
import Steps from "../components/Steps";
import Notice from "../components/Notice";
import fetches from "../utils/request";
import localDb from "../utils/localDb";
import { getVerify } from "../utils/api";
const { defaultHost } = fetches;
export default {
  name: "Signup",
  inject: ["reload"], //注入reload方法
  components: {
    Steps,
    Notice,
  },
  data() {
    return {
      isEditInfos: false,
      editTitle: "",
      isShow: true,
      isShowExample: false,
      alertTitle: "",
      signInfo: [], //图片上传页面的基本数据
      requireImg: [], //必填项照片数组
    };
  },
  methods: {
    iconChoose(type) {
      switch (type) {
        case "1":
          return "icon_hkb";
        case "4":
          return "icon_zf";
        case "11":
          return "icon_qtcl";
        case "12":
          return "icon_cjzm";
        default:
          return "icon_qtcl";
      }
    },
    //图片上传地址
    uploadUrl() {
      return `${defaultHost}/api/Student/UploadImage`;
    },
    onSubmit() {
      for (let i = 0; i < this.requireImg.length; i++) {
        if (!this.requireImg[i].regImages.length) {
          this.$toast("请上传" + this.requireImg[i].imgTitle);
          return false;
        }
      }
      if (this.isEditInfos) {
        Toast.success({
          message: "修改成功",
          duration: 1500,
        });
        setTimeout(() => {
          this.$router.push({ path: "/results" });
        }, 1500);
      } else {
        this.$router.push({ path: "/selectgrade" });
      }
    },
    //图片格式限制
    beforeAvatarUpload(file) {
      let isJPG = null;
      if (file.length > 1) {
        for (let j = 0; j < file.length; j++) {
          if (
            file[j].type === "image/jpeg" ||
            file[j].type === "image/jpg" ||
            file[j].type === "image/png"
          ) {
            isJPG =
              file[j].type === "image/jpeg" ||
              file[j].type === "image/jpg" ||
              file[j].type === "image/png";
          } else {
            isJPG = false;
            return;
          }
        }
      } else {
        isJPG =
          file.type === "image/jpeg" ||
          file.type === "image/jpg" ||
          file.type === "image/png";
      }
      file.deg = 0;
      if (!isJPG) {
        Toast("上传图片只能是 JPG或PNG 格式!");
      }
      return isJPG;
    },
    //图片大小限制
    onOversize(file) {
      //const isLt3M = file.size / 1024 / 1024 < 3;
      //if (!isLt3M) {
      Toast("上传图片大小不能超过 5MB!");
      //}
      //return isLt3M;
    },
    //上传图片
    handleHttpRequest(file, imgType) {
      if (this.verify.res == -1) {
        this.$toast(this.verify.msg);
        this.getSignupInfo();
        return false;
      }
      let formData = new FormData();
      if (file instanceof Array && file.length) {
        // 判断是否是多图上传 多图则循环添加进去
        file.forEach((item) => {
          formData.append("file", item.file); //第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
        });
      } else {
        formData.append("file", file.file);
      }
      formData.append("imagetype", imgType);
      localDb.set("upload", "upload");
      Toast.loading({
        message: "上传中...",
        forbidClick: true,
        duration: 0,
      });
      this.$fetch(
        `/api/Student/UploadImage?imageType=${imgType}`,
        formData,
        "post"
      )
        .then((data) => {
          if (data.res == 0) {
            Toast.clear();
            Toast.success({
              message: "上传成功",
              duration: 1000,
            });
            localDb.clear("1", "upload");
            //this.reload();
            this.getSignupInfo();
          } else {
            localDb.clear("1", "upload");
            this.$toast(data.msg);
          }
        })
        .catch(() => {
          this.getPhotoList();
          Toast.fail("上传失败");
        });
    },
    //删除图片
    handleRemove(file, fileList) {
      if (this.verify.res == -1) {
        this.$toast(this.verify.msg);
        return false;
      }
      Dialog.confirm({
        title: "提示",
        message: "确定删除这张图片吗?",
      }).then(() => {
        this.$fetch(
          `/api/Student/DelUploadImage?id=${file.id}&type=${file.imgSource}`,
          {},
          "post"
        ).then((data) => {
          if (data.res == 0) {
            Toast.success({
              message: "删除成功",
              duration: 1000,
            });
            //this.reload();
            this.getSignupInfo();
          } else {
            this.$toast(data.msg);
          }
        });
      });
    },
    //获取图片上传页面数据
    getSignupInfo() {
      this.$fetch("/api/Student/GetRegImageSet", "get").then((data) => {
        if (data.res == 0) {
          this.isShowExample = data.data.imgOpen == "0" ? false : true;
          this.signInfo = data.data.studRegImageSet;
          this.requireImg = [];
          this.signInfo.forEach((item) => {
            item.regImages.forEach((val) => {
              val.url = defaultHost + val.imgUrl;
            });
            if (item.isRequired == "1") {
              this.requireImg.push({
                imgTitle: item.imgTitle,
                regImages: item.regImages,
              });
            }
          });
        }
      });
    },
    getRegType(type) {
      this.$fetch("/api/Student/GetSysCode", { type: type }, "get").then(
        (data) => {
          if (data.res == 0) {
            // console.log(data);
            data.data.forEach((item) => {
              if (item.code == this.stuList.regType) {
                this.alertTitle = item.text;
              }
            });
          }
        }
      );
    },
    // 获取学生信息
    getStuList() {
      this.$fetch("/api/Student/GetStudInfo", {}, "get").then((data) => {
        if (data.res == 0) {
          this.$store.dispatch("setStuList", data.data.person);
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    // 判断学生是否可修改信息、注销
    async getVerify() {
      try {
        const data = await getVerify();
        localDb.set("verify", data);
      } catch (error) {}
    },
  },
  computed: {
    stuList() {
      return this.$store.state.stuList;
    },
    verify() {
      return this.$store.state.verify;
    },
  },
  created() {
    this.getVerify();
    //判断是不是修改页面
    if (this.$route.query.isEditInfos) {
      this.isEditInfos = true;
      this.editTitle = this.$route.query.isEditInfos;
    } else {
      this.isEditInfos = false;
    }
  },
  mounted() {
    this.getRegType("regType1");
    this.getSignupInfo();
    this.getStuList();
    // if(this.verify.res!=0){
    //     this.$toast(this.verify.msg);
    // }
  },
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.reporting-main {
  padding: 0 10px;
  border-radius: 10px;
  overflow: hidden;
  .uploader-box {
    padding: 30px 0;
    text-align: left;
    padding-bottom: 0;
  }
  .list-bd {
    padding-right: 0;
    .info {
      padding-right: 30px;
      margin-top: -20px;
    }
  }
}
.van-popup {
  width: 630px;
  // height: 912px;
  overflow: hidden;
  border-radius: 10px;
  .exam-title {
    padding: 0 30px;
    height: 80px;
    line-height: 80px;
    text-align: left;
    font-size: 36px;
    background-color: #f5f5f5;
  }
  .exam-content {
    ul {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;
      padding: 30px 15px 0;
      li {
        width: 270px;
        padding: 0 15px 20px;
        .content-img {
          background-color: #e5f4ff;
          padding: 0 15px;
          font-size: 0;
          margin-bottom: 15px;
          border-radius: 4px;
          span {
            font-size: 28px;
            line-height: 53px;
            color: #222;
          }
          .van-image {
            width: 240px;
            height: 180px;
          }
        }
        .icon_dx {
          width: 70px;
          height: 68px;
        }
      }
    }
    .know {
      margin: 0 20px 20px;
      width: 590px;
      height: 90px;
      font-size: 36px;
      border-radius: 10px;
    }
  }
}
.form-btn {
  width: 105%;
  margin-left: -10px;
  margin-top: 30px;
  .van-button {
    width: 50%;
    height: 90px;
    font-size: 36px;
    border-radius: unset;
    // margin-top: 30px;
    &:first-child {
      background-color: #fff;
      border: none;
      border-top: 1px solid #ccc;
      color: #222;
    }
  }
}
.van-uploader {
  &.limit-uploader {
    /deep/ .van-uploader__upload {
      display: none;
    }
  }
}
</style>
<style lang="scss">
.uploader-box {
  .van-uploader__preview-image {
    width: 210px;
    height: 210px;
  }
  .van-uploader__preview {
    margin: 0 20px 30px 0;
  }
  .van-uploader__upload {
    width: 210px;
    height: 210px;
    margin: 0 0 30px 0;
  }
}
.form-edit-btn {
  width: 105%;
  margin-left: -10px;
  margin-top: 30px;
  .van-button {
    // margin-top: 20px;
    width: 100%;
    height: 90px;
    font-size: 36px;
  }
}
</style>
